package com.htpcremote;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public final class HTPCRemote extends BaseActivity {
	private static final String TAG = "HTPCRemote";

	//
	private EditText tbIp;
	//
	private ListView mHostlist;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.main);
		// set some listeners
		Button but = (Button)this.findViewById(R.id.btnConnect);
		but.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				onConnectButton();
			}
		});

		// check SharedPreferences for IP
		Settings.init(this.getApplicationContext());

		mHostlist = (ListView) findViewById(R.id.lvHosts);
		populateHostList();

		//
		this.tbIp = (EditText)this.findViewById(R.id.etIp);
		if (Settings.ip != null) {
			this.tbIp.setText(Settings.ip);
		}
	}

	private void populateHostList() {
		// populates the host list with saved hosts from the settings
		LinkedList<String> ips = Settings.savedHosts;
		String[] from = new String[]{"hostip"};
		int[] to = new int[]{R.id.hostEntry};
		List<Map<String,String>> data = new ArrayList<Map<String, String>>();
		for (String s:ips){
			Map<String, String> map = new HashMap<String, String>();
			map.put("hostip", s);
			data.add(map);
		}

		/**
		 * in order to be able to hook up the onclick listeners for 
		 * the children of the simple adapter, we have to override the 
		 * getView() method to set the listeners we want, so callbacks
		 * can function correctly
		 */

		SimpleAdapter adapter = new SimpleAdapter(this,data,R.layout.savedhost,from,to){
			@Override
			public View getView(int position, View convertView, ViewGroup parent){
				View v = super.getView(position, convertView, parent);
				TextView text = (TextView) v.findViewById(R.id.hostEntry);
				final CharSequence str = text.getText();
				ImageButton b = (ImageButton) v.findViewById(R.id.hostbutton);

				// set the listener for clicking on the text
				text.setOnClickListener(new View.OnClickListener() {

					public void onClick(View v) {
						onSavedHost(str); 
					}
				});

				// set the listener for clicking on the delete button
				b.setOnClickListener(new View.OnClickListener() {     				

					public void onClick(View v) { 
						onRemoveSavedHost(str);
					}
				});

				return v;
			}
		};

		mHostlist.setAdapter(adapter);

	}

	/** App starts anything it needs to start */
	public void onStart() {
		super.onStart();
		Context context = this.getApplicationContext();
		WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		if (!wifiManager.isWifiEnabled()) {
			wifiManager.setWifiEnabled(true);
		}
	}

	private void onConnectButton() {
		String ip = this.tbIp.getText().toString();
		if (ip.matches("^[0-9]{1,4}\\.[0-9]{1,4}\\.[0-9]{1,4}\\.[0-9]{1,4}$")) {
			try {
				Settings.setIp(ip);
				//
				Intent i = new Intent(this, PadActivity.class);
				this.startActivity(i);
				this.finish();
			} catch (Exception ex) {
				//this.tvError.setText("Invalid IP address");
				//this.tvError.setVisibility(View.VISIBLE);
				Toast.makeText(this, this.getResources().getText(R.string.toast_invalidIP), Toast.LENGTH_LONG).show();
				Log.d(TAG, ex.toString());
			}
		} else {
			//this.tvError.setText("Invalid IP address");
			//this.tvError.setVisibility(View.VISIBLE);
			Toast.makeText(this, this.getResources().getText(R.string.toast_invalidIP), Toast.LENGTH_LONG).show();
		}
	}

	private void onRemoveSavedHost(CharSequence str) {
		try {
			Settings.removeSavedHost(str); 
			populateHostList();
			// TODO: we should be able to just call _below_ to update the view
			// however, the DataSetObserver is locked onto a copy of the data,
			// not a reference (from Settings). This needs to be changed...
			//((SimpleAdapter)mHostlist.getAdapter()).notifyDataSetChanged();

		} catch (Exception e) {
			Log.d(TAG,"couldnt remove "+str.toString()+" from list: "+e.toString());
		}

	}

	private void onSavedHost(CharSequence s) {
		try {
			tbIp.setText(s);
		} catch (Exception e) {
			Log.d(TAG,e.toString());
		}

	}
}
